package io.bdmc.modules.bss.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.bdmc.common.annotation.SysLogger1;
import io.bdmc.common.utils.*;
import io.bdmc.common.utils.Constant.ModifyName;
import io.bdmc.modules.bss.entity.DeviceFibreMatch;
import io.bdmc.modules.bss.entity.FibreCablePoint;
import io.bdmc.modules.bss.entity.FibreFibre;
import io.bdmc.modules.bss.service.IDeviceFibreMatchService;
import io.bdmc.modules.bss.service.IFibreCablePointService;
import io.bdmc.modules.bss.service.IFibreFibreService;
import io.bdmc.modules.sys.controller.AbstractController;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 光缆 前端控制器
 * </p>
 *
 * @author ping
 * @since 2020-06-30
 */

// "光缆", description = "/bss/fibre/fibre")
@RestController
@RequestMapping("/bss/fibre/fibre")
public class FibreFibreController extends AbstractController {

	@Autowired
	IFibreFibreService _fibrefibreSvs;

	@Autowired
	IFibreCablePointService _pointSvs;

	@Autowired
	IDeviceFibreMatchService _matchSvs;

	// "查询所有光缆", notes = "查询所有光缆")
	@GetMapping("/list")
	public R list() {
		// int deptId = getDeptId().intValue();
		MyPage<FibreFibre> myPage = new MyPage<>(1, 20000);
		MyPage<FibreFibre> map = _fibrefibreSvs.mySelectPage(myPage);
		return R.ok().putData(map.getRecords());
	}

	// "当前部门下的线路ztree", notes = "当前部门下的线路ztree")
	@GetMapping("/ztree")
	public R ztree() {
		int deptId = getDeptId().intValue();
		return R.ok().putData(_fibrefibreSvs.ztree(deptId));
	}

	// "光缆信息", notes = "光缆信息")
	@GetMapping("/info")
	public R info(int fibreId) {
		return R.ok().putData(_fibrefibreSvs.getById(fibreId));
	}

	@SysLogger1(value = "新增光缆", entityType = FibreFibre.class, operationType = ModifyName.ADD)
	@PostMapping("/save")
	// "新增FibreFibre", notes = "新增光缆")
	@RequiresPermissions("bss:fibre:fibre:save")
	public R save(@RequestBody FibreFibre fibrefibre) {
		fibrefibre.setFibreId(null);
		fibrefibre.setCreateBy(getUser().getUsername());
		fibrefibre.setCreateTime(LocalDateTime.now());
		Boolean b = fibrefibre.insert();
		return R.trueOrFalse(b);
	}

	@SysLogger1(value = "修改光缆", entityType = FibreFibre.class, operationType = ModifyName.UPDATE)
	@PostMapping("/update")
	// "修改FibreFibre", notes = "修改光缆")
	@RequiresPermissions("bss:fibre:fibre:update")
	public R update(@RequestBody FibreFibre fibrefibre) {
		final FibreFibre dbFibre = _fibrefibreSvs.getById(fibrefibre.getFibreId());
		if (!dbFibre.getFibreName().equals(fibrefibre.getFibreName())) {
			_matchSvs.update(new UpdateWrapper<DeviceFibreMatch>().eq("fibre_id", fibrefibre.getFibreId())
					.set("fibre_name", fibrefibre.getFibreName()));
		}
		Boolean b = fibrefibre.updateById();
		return R.trueOrFalse(b);
	}

	@SysLogger1(value = "删除光缆", entityType = FibreFibre.class, operationType = ModifyName.DELETE)
	@PostMapping("/delete")
	// "删除FibreFibre", notes = "删除光缆")
	@RequiresPermissions("bss:fibre:fibre:delete")
	public R delete(@RequestBody long fibreId) {
		if (fibreId > 0) {
			_fibrefibreSvs.removeById(fibreId);
			_pointSvs.remove(new QueryWrapper<FibreCablePoint>().eq("fibre_id", fibreId));
			_matchSvs.remove(new QueryWrapper<DeviceFibreMatch>().eq("fibre_id", fibreId));
		}

		return R.ok();
	}

	// "combo", notes = "combo")
	@GetMapping("/combo")
	public R combo() {
		return R.ok().putData(_fibrefibreSvs.combo(getDeptId().intValue()));
	}

	@RequestMapping(value = "export")
	public R export() throws IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("光缆列表");
		List<FibreFibre> list = _fibrefibreSvs.list();
		String dateString = DateUtils.formatLocalDateTime(LocalDateTime.now(), DateUtils.Pay_DATE_TIME_PATTERN);
		String fileName = "光缆统计" + dateString + ".xls";// 设置要导出的文件的名字

		Map<String, CellStyle> styles = ExcelImport.createStyles(workbook);

		// 新增数据行，并且设置单元格数据
		int rowNum = 0;
		String[] headers = { "序号", "光缆名称", "光缆编码", "光缆类型", "纤芯数量", "光缆型号", "光缆长度(km)", "生产厂家", "投运时间", "维护单位及电话",
				"备注" };

		rowNum = ExcelImport.initialize(rowNum, "光缆信息报表", headers, workbook, sheet, styles);

		// 在表中存放查询到的数据放入对应的列
		int dataIndex = 1;
		for (FibreFibre f : list) {
			HSSFRow row1 = sheet.createRow(rowNum++);
			row1.createCell(0).setCellValue(dataIndex);
			row1.createCell(1).setCellValue(f.getFibreName());
			row1.createCell(2).setCellValue(ExcelImport.convertNullString(f.getFibreCode()));
			row1.createCell(3).setCellValue(ExcelImport.convertNullString(f.getFibreLevel()));
			row1.createCell(4).setCellValue(ExcelImport.convertNullString(f.getCoreCount()));
			row1.createCell(5).setCellValue(ExcelImport.convertNullString(f.getFibreModel()));
			row1.createCell(6).setCellValue(ExcelImport.convertNullString(f.getFibreLength()));
			row1.createCell(7).setCellValue(ExcelImport.convertNullString(f.getSupplier()));
			row1.createCell(8).setCellValue(ExcelImport.convertNullString(f.getOperationDate()));
			row1.createCell(9).setCellValue(ExcelImport.convertNullString(f.getServiceMobile()));
			row1.createCell(10).setCellValue(ExcelImport.convertNullString(f.getRemark()));
			dataIndex++;
		}
		try {
			File path = new File(Constant.EXPORTPATH);
			if (!path.exists()) {
				path.mkdir();
			}
			File f = new File(path.getAbsolutePath() + "/excel/", fileName);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdir();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(f);// 指定路径与名字和格式
			workbook.write(fileOutputStream);// 将数据写出去
			fileOutputStream.close();// 关闭输出流
			return R.ok().putData("/excel/" + fileName);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error(-1, e.getMessage());
		}
	}

}
